package cn.hfatec.shms.system.notice.action;

import cn.hfatec.shms.cache.CodeInfoCache;
import cn.hfatec.shms.constants.ShmsConstant;
import cn.hfatec.shms.enums.CodeType;
import cn.hfatec.shms.exception.NotAuthException;
import cn.hfatec.shms.system.user.model.User;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.Arrays;
import javax.annotation.Resource;


import cn.hfatec.JsonResponse;
import cn.hfatec.Page;
import cn.hfatec.Table;
import cn.hfatec.constants.SysContant;
import cn.hfatec.freemarker.FreeMarkerUtil;
import cn.hfatec.shms.system.notice.model.NoticeParams;
import cn.hfatec.shms.system.notice.model.Notice;
import cn.hfatec.shms.system.notice.service.NoticeService;
import cn.hfatec.shms.base.ShmsBaseAction;
import org.springframework.ui.Model;
import javax.validation.Valid;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;



/**
 *
 * @author hfatec codegen
 * @version 1.0
 *
 * the JAVA code is generate by middlegen
 *
 */
@Controller
@RequestMapping("/system/notice")
public class NoticeAction extends ShmsBaseAction {

    //服务层
    @Resource(name = "NoticeService")
    private NoticeService noticeService;


    /**
     *
     * 查询列表
     *
     */
    @RequestMapping("/list")
    public String list(NoticeParams noticeParams, Page page, Model model,HttpServletRequest request) throws NotAuthException {
        User user = (User) request.getSession().getAttribute(SysContant.LOGIN_USER_SESSION);
        if (user == null) {
            throw new NotAuthException("用户未授权");
        }
        noticeParams.setReceiveUserId(user.getLoginName());
        Table table = noticeService.queryNoticeTable(noticeParams, page);
        model.addAttribute("noticesTable", table);
        model.addAttribute("noticeParams", noticeParams);
        model.addAttribute("isReadList", CodeInfoCache.getCodeInfo(CodeType.YES_OR_NO));
        return "/system/notice/list";
    }

    /**
     *
     * 异步查询列表
     *
     */
    @RequestMapping("/ajaxList")
    @ResponseBody
    public String ajaxList(NoticeParams noticeParams, Page page, Model model,HttpServletRequest request) {
        try {
            list(noticeParams, page, model,request);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/notice/table", model)).toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }
    /**
     *
     * 跳转到阅读页
     *
     */
    @RequestMapping("/goNotice")
    @ResponseBody
    public String goEdit(Integer id,Model model) {
        try {
            Notice notice = noticeService.getNotice(id);
            model.addAttribute("notice", notice);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/notice/reader", model)).toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }
/**
     *
     * 修改阅读状态
     *
     */

    @RequestMapping("/goReader")
    @ResponseBody
    public String goReader(Integer id) {
        try {
            Notice notice = noticeService.getNotice(id);
            notice.setIsRead(1);
            noticeService.saveNotice(notice);
        } catch(Exception e) {
            e.printStackTrace();
            logger.error("数据" + id + "删除异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.DELETE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse(JsonResponse.RETURN_SUCCESS, SysContant.DELETE_SUCCESS_MESSAGE).toString();
    }


    /**
     *
     * 根据IDs删除数据
     *
     */
    @RequestMapping("/delete")
    @ResponseBody
    public String deleteNotice(String ids) {
        try {
            List<String> idList = new ArrayList<String>();
            if(ids.length() > 0) {
                idList = Arrays.asList(ids.split(","));
            }
            noticeService.deleteNoticeBatch(idList);
        } catch(Exception e) {
            e.printStackTrace();
            logger.error("数据" + ids + "删除异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.DELETE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse(JsonResponse.RETURN_SUCCESS, SysContant.DELETE_SUCCESS_MESSAGE).toString();
    }

    /**
     *
     * 保存数据
     *
     */
    @RequestMapping("/save")
    @ResponseBody
    public String saveNotice(@Valid Notice notice, BindingResult result) {

        try {
            if(result.hasErrors()) {
                List<ObjectError> errors = result.getAllErrors();
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, errors.get(0).getDefaultMessage()).toString();
            }
            noticeService.saveNotice(notice);
        } catch(Exception e) {
            e.printStackTrace();
            logger.error("数据Notice保存异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.SAVE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, SysContant.SAVE_SUCCESS_MESSAGE).toString();
    }

    /**
     *
     * 应的最根据登录用户，获取对新6条系统消息
     *
     * @return
     */
    @RequestMapping("/ajaxNewsList")
    @ResponseBody
    public String listNews(NoticeParams noticeParams,Model model,HttpServletRequest request) {
        try {
            User user = (User)request.getSession().getAttribute(SysContant.LOGIN_USER_SESSION);
            if(user == null) {
                throw new NotAuthException("用户未授权");
            }

            Page page = new Page();
            noticeParams.setReceiveUserId(user.getLoginName());
            page.setPageSize(6);
            page.setCurrentPage(1);
            Table table = noticeService.queryNoticeTable(noticeParams,page);
            List newsList=table.getRows();
            noticeParams.setIsRead(ShmsConstant.IS_RED_NO);
            List totalNewsList = noticeService.queryNoticeList(noticeParams);
            model.addAttribute("newsList", newsList);
            model.addAttribute("totalNewsList", totalNewsList);
            model.addAttribute("user", user);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/notice/news", model)).toString();
        } catch(Exception e) {
            e.printStackTrace();
            logger.error("数据加载异常！");
        }
        return JsonResponse.error;
    }
}
